package com.burstly.lib.component.networkcomponent.burstly.html.mraid;

import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import com.burstly.lib.util.LoggerExt;
import com.burstly.lib.util.Utils;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;

class AddAssetEvent extends MraidEvent
  implements DialogInterface.OnClickListener
{
  static final int EVENT_ID = 9;
  static final LoggerExt LOG = LoggerExt.getInstance();
  static final String TAG = AddAssetEvent.class.getSimpleName();
  private ExecutorService mExecutor;
  private final Object mLock = new Object();
  MraidView mView;

  private static void checkInterrupted()
    throws InterruptedException
  {
    if (Thread.currentThread().isInterrupted())
      throw new InterruptedException("Asset's download has been cancelled.");
  }

  private static String getExtensionFromContentType(HttpResponse paramHttpResponse)
  {
    Header localHeader = paramHttpResponse.getFirstHeader("Content-Type");
    String str1 = null;
    HeaderElement[] arrayOfHeaderElement;
    int i;
    if (localHeader != null)
    {
      arrayOfHeaderElement = localHeader.getElements();
      i = arrayOfHeaderElement.length;
    }
    for (int j = 0; ; j++)
    {
      str1 = null;
      if (j < i)
      {
        String str2 = arrayOfHeaderElement[j].getName();
        if (!str2.contains("/"))
          continue;
        String[] arrayOfString = str2.split("/");
        int k = arrayOfString.length;
        str1 = null;
        if (k > 1)
          str1 = arrayOfString[1];
      }
      return str1;
    }
  }

  static String getFileName(String paramString, HttpResponse paramHttpResponse)
  {
    Header localHeader = paramHttpResponse.getFirstHeader("Content-Disposition");
    if (localHeader != null)
      for (HeaderElement localHeaderElement : localHeader.getElements())
        if (localHeaderElement.getName().equals("filename"))
          return localHeaderElement.getValue();
    StringBuilder localStringBuilder = new StringBuilder(UUID.randomUUID().toString().substring(0, 8));
    String str = getExtensionFromContentType(paramHttpResponse);
    if (str != null)
      localStringBuilder.append(".").append(str);
    while (true)
    {
      return localStringBuilder.toString();
      LOG.logWarning(TAG, "Could not determine {0} the file extension and type. The file will be written to SD card as is with no extension.", new Object[] { paramString });
    }
  }

  protected void cleanUp()
  {
    super.cleanUp();
    if (this.mExecutor != null)
    {
      this.mExecutor.shutdownNow();
      this.mExecutor = null;
    }
  }

  void fireError(String paramString)
  {
    this.mView.fireErrorEvent("storePicture", paramString);
  }

  public void fireEvent(final MraidView paramMraidView, Object[] paramArrayOfObject)
  {
    if (!checkArgs(paramArrayOfObject))
      return;
    if (!Utils.canWriteToSDCard())
    {
      LOG.logDebug(TAG, "SD card is not available. Skipped file saving", new Object[0]);
      fireError("Sd card is not available");
      return;
    }
    this.mView = paramMraidView;
    final String str = (String)paramArrayOfObject[0];
    new AlertDialog.Builder(paramMraidView.getContext()).setTitle("Confirm adding new asset").setMessage("The creative is going to add a new media to your media library. Allow ?\nMedia url is: " + str).setCancelable(false).setPositiveButton("Yes", new DialogInterface.OnClickListener()
    {
      public void onClick(DialogInterface paramAnonymousDialogInterface, int paramAnonymousInt)
      {
        AddAssetEvent.this.saveAsset(paramMraidView.getContext(), str);
      }
    }).setNegativeButton("No", this).show();
  }

  public void onClick(DialogInterface paramDialogInterface, int paramInt)
  {
    if (paramInt == -2)
      fireError("User cancelled");
  }

  void saveAsset(Context paramContext, final String paramString)
  {
    if (this.mExecutor == null)
      this.mExecutor = Executors.newSingleThreadExecutor();
    this.mExecutor.submit(new Runnable()
    {
      public void run()
      {
        try
        {
          HttpResponse localHttpResponse = Utils.makeGetRequest(paramString);
          int i = localHttpResponse.getStatusLine().getStatusCode();
          HttpEntity localHttpEntity = localHttpResponse.getEntity();
          long l = localHttpEntity.getContentLength();
          if ((i != 200) || (l == 0L))
          {
            LoggerExt localLoggerExt = AddAssetEvent.LOG;
            String str1 = AddAssetEvent.TAG;
            Object[] arrayOfObject = new Object[3];
            arrayOfObject[0] = paramString;
            arrayOfObject[1] = Integer.valueOf(i);
            arrayOfObject[2] = Long.valueOf(l);
            localLoggerExt.logWarning(str1, "Error downloading media url {0}\nResponse code {1}\nContent length {2}", arrayOfObject);
            AddAssetEvent.this.fireError("Error downloading media url " + paramString);
            return;
          }
          String str2 = AddAssetEvent.getFileName(paramString, localHttpResponse);
          AddAssetEvent.this.tryToStore(localHttpEntity, str2);
          return;
        }
        catch (Exception localException)
        {
          AddAssetEvent.LOG.logDebug(AddAssetEvent.TAG, localException.getMessage(), new Object[0]);
          AddAssetEvent.this.fireError(localException.getMessage());
        }
      }
    });
  }

  void tryToStore(HttpEntity paramHttpEntity, String paramString)
    throws Exception
  {
    ByteBuffer localByteBuffer = ByteBuffer.allocate(16384);
    ReadableByteChannel localReadableByteChannel = Channels.newChannel(paramHttpEntity.getContent());
    File localFile1 = new File(Environment.getExternalStorageDirectory(), "customAssets");
    if ((!localFile1.exists()) && (!localFile1.mkdir()))
      throw new Exception("Could not create output directory on SD card {0} to store the asset" + localFile1.getName());
    File localFile2 = new File(localFile1, paramString);
    FileChannel localFileChannel = new FileOutputStream(localFile2).getChannel();
    try
    {
      if (localReadableByteChannel.read(localByteBuffer) > 0)
      {
        localByteBuffer.flip();
        localFileChannel.write(localByteBuffer);
        localByteBuffer.clear();
        checkInterrupted();
      }
    }
    finally
    {
      Utils.closeStream(localFileChannel);
      Utils.closeStream(localReadableByteChannel);
    }
    synchronized (this.mLock)
    {
      Intent localIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
      localIntent.setData(Uri.fromFile(localFile2));
      this.mView.getContext().sendBroadcast(localIntent);
      return;
    }
  }
}

/* Location:           E:\android\Toy Defense 2_dex2jar.jar
 * Qualified Name:     com.burstly.lib.component.networkcomponent.burstly.html.mraid.AddAssetEvent
 * JD-Core Version:    0.6.2
 */